import React, { useMemo, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import DOMPurify from 'dompurify';
import {
  Row,
  Col,
  Card,
  Statistic,
  Avatar,
  Typography,
  Space,
  List,
  Tabs,
  Tag,
  Descriptions,
  Alert,
  Button
} from 'antd';
import {
  AppstoreOutlined,
  ThunderboltOutlined,
  PrinterOutlined,
  TeamOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons';
import './home.css';

export default function Home() {
  const { Title, Text } = Typography;

  // 模拟用户与首页数据
  const [userStore] = useState({
    nickName: '商户A',
    account: 'merchantA',
    avatar: '/vite.svg',
    loginIp: '127.0.0.1',
    currencySymbol: '¥',
  });

  const [indexInfo] = useState({
    machineTotal: 888,
    renewalMachineTotal: 120,
    printerTotal: 33,
    temporaryTotal: 18,
    yesterdayProfit: 320.56,
    thisWeekProfit: 1260.24,
    lastWeekProfit: 980.12,
    thisMonthProfit: 4520.67,
    lastMonthProfit: 4980.0,
    totalIncome: 98765.43,
    printPoints: 15678,
    wallet: 205.78,
    activityNum: 5,
    expireTime: '2025-12-31 23:59:59',
    remainTime: '83天10小时',
    todayProfit: 320.12,
  });

  const [activityList] = useState([
    { id: 1, name: '新春促销活动', startTime: '2025-02-01 09:00:00', endTime: '2025-02-15 23:59:59' },
    { id: 2, name: '打印积分翻倍', startTime: '2025-03-01 09:00:00', endTime: '2025-03-07 23:59:59' },
    { id: 3, name: '会员拉新奖励', startTime: '', endTime: '' },
    { id: 4, name: '设备升级提示', startTime: '', endTime: '' },
    { id: 5, name: '夏季主题活动', startTime: '2025-06-01 09:00:00', endTime: '2025-06-30 23:59:59' },
  ]);

  const [noticeInfo] = useState([
    {
      type: 3,
      name: '公告',
      list: [
        { id: 'n1', title: '系统更新公告', content: '<p>本次更新提升了系统稳定性。</p>', createTime: '2025-10-01' },
        { id: 'n2', title: '维护通知', content: '<p>本周末将进行短暂维护。</p>', createTime: '2025-10-05' },
      ],
    },
    {
      type: 2,
      name: '消息',
      list: [{ id: 'n3', title: '营销消息', content: '<p>双11活动即将开启，敬请期待！</p>', createTime: '2025-10-08' }],
    },
    {
      type: 1,
      name: '提醒',
      list: [{ id: 'n4', title: '合同到期提醒', content: '<p>您的某些合同即将到期。</p>', createTime: '2025-10-02' }],
    },
  ]);

  const [nowNoticeType, setNowNoticeType] = useState(3);

  const trendOption = useMemo(
    () => ({
      tooltip: { trigger: 'axis' },
      legend: { top: '5%' },
      xAxis: [
        {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        },
      ],
      yAxis: [{ type: 'value' }],
      series: [
        {
          name: '收入趋势',
          type: 'line',
          areaStyle: {},
          data: [200, 320, 520, 550, 600, 805, 888, 950, 1300, 2503, 2702, 2712],
        },
      ],
    }),
    []
  );

  function handlerToMoreActivity() {
    // 预留到活动列表页
    // TODO: 路由跳转到活动列表
  }

  function handlerToActivityDetail(item) {
    // TODO: 路由跳转到活动详情
    console.log('进入活动详情：', item.name);
  }

  function sanitize(html) {
    return { __html: DOMPurify.sanitize(html || '') };
  }

  const noticeTabs = [3, 2, 1].map((type) => ({
    key: String(type),
    label: noticeInfo.find((n) => n.type === type)?.name || String(type),
    children: (
      <List
        itemLayout="vertical"
        dataSource={noticeInfo.find((n) => n.type === type)?.list || []}
        renderItem={(notice) => (
          <List.Item>
            <List.Item.Meta
              title={<Text strong>{notice.title || '无标题'}</Text>}
              description={<Text type="secondary">{notice.createTime}</Text>}
            />
            <div dangerouslySetInnerHTML={sanitize(notice.content)} />
          </List.Item>
        )}
      />
    ),
  }));

  const up = indexInfo.yesterdayProfit >= 0;

  return (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={10}>
          <Card>
            <Space align="center">
              <Avatar size={64} src={userStore.avatar} />
              <div>
                <Title level={4} style={{ margin: 0 }}>
                  Hello, {userStore.nickName || userStore.account}
                </Title>
                <Text type="secondary">登录IP：{userStore.loginIp || '未知'}</Text>
              </div>
            </Space>
            <div style={{ marginTop: 12 }}>
              <Text>欢迎使用商户端后台，祝您工作顺利！如需帮助，请联系管理员。</Text>
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={14}>
          <Row gutter={[16, 16]}>
            <Col xs={12} md={6}>
              <Card>
                <Space>
                  <AppstoreOutlined />
                  <Statistic title="设备总数" value={indexInfo.machineTotal} />
                </Space>
              </Card>
            </Col>
            <Col xs={12} md={6}>
              <Card>
                <Space>
                  <ThunderboltOutlined />
                  <Statistic title="续费设备" value={indexInfo.renewalMachineTotal} />
                </Space>
              </Card>
            </Col>
            <Col xs={12} md={6}>
              <Card>
                <Space>
                  <PrinterOutlined />
                  <Statistic title="打印机总数" value={indexInfo.printerTotal} />
                </Space>
              </Card>
            </Col>
            <Col xs={12} md={6}>
              <Card>
                <Space>
                  <TeamOutlined />
                  <Statistic title="临时访客" value={indexInfo.temporaryTotal} />
                </Space>
              </Card>
            </Col>
          </Row>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={10}>
          <Card title="收益概览" extra={<Text type="secondary">{up ? '昨日收益上涨' : '昨日收益下降'}</Text>}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Statistic
                  title="今日收益"
                  value={indexInfo.todayProfit}
                  precision={2}
                  prefix={userStore.currencySymbol}
                  suffix={up ? <ArrowUpOutlined style={{ color: '#52c41a' }} /> : <ArrowDownOutlined style={{ color: '#ff4d4f' }} />}
                />
              </Col>
              <Col span={12}>
                <Statistic title="本周收益" value={indexInfo.thisWeekProfit} precision={2} prefix={userStore.currencySymbol} />
              </Col>
              <Col span={12}>
                <Statistic title="本月收益" value={indexInfo.thisMonthProfit} precision={2} prefix={userStore.currencySymbol} />
              </Col>
              <Col span={24}>
                <Statistic title="累计收入" value={indexInfo.totalIncome} precision={0} prefix={userStore.currencySymbol} />
              </Col>
            </Row>

            <div style={{ marginTop: 16 }}>
              <Descriptions column={1} size="small" title="打印统计">
                <Descriptions.Item label="打印点数">{indexInfo.printPoints}</Descriptions.Item>
                <Descriptions.Item label="钱包余额">
                  {userStore.currencySymbol}
                  {indexInfo.wallet.toFixed(2)}
                </Descriptions.Item>
                <Descriptions.Item label="活动数量">
                  <Tag color="blue">{indexInfo.activityNum}</Tag>
                </Descriptions.Item>
              </Descriptions>
              {indexInfo.expireTime && (
                <Alert
                  style={{ marginTop: 8 }}
                  type="warning"
                  message={
                    <Space>
                      <span>套餐到期时间：{indexInfo.expireTime}</span>
                      <Tag color="orange">剩余时间：{indexInfo.remainTime}</Tag>
                    </Space>
                  }
                  showIcon
                />
              )}
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={7}>
          <Card title="活动" extra={<Button type="link" onClick={handlerToMoreActivity}>更多活动 +</Button>}>
            <List
              dataSource={activityList}
              renderItem={(item) => (
                <List.Item onClick={() => handlerToActivityDetail(item)} style={{ cursor: 'pointer' }}>
                  <List.Item.Meta
                    title={<Text>活动：{item.name}</Text>}
                    description={
                      item.startTime && item.endTime ? (
                        <Space>
                          <Tag>{item.startTime.split(' ')[0]}</Tag>
                          <span>-</span>
                          <Tag>{item.endTime.split(' ')[0]}</Tag>
                        </Space>
                      ) : (
                        <Tag color="default">时间未定</Tag>
                      )
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        <Col xs={24} lg={7}>
          <Card>
            <Tabs activeKey={String(nowNoticeType)} onChange={(key) => setNowNoticeType(Number(key))} items={noticeTabs} />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card title="收入趋势">
            <ReactECharts option={trendOption} style={{ height: 400 }} />
          </Card>
        </Col>
      </Row>
    </Space>
  );
}